/*
 * OperationResult.java
 *
 * $Id: OperationResult.java,v 1.1 2008-06-26 10:42:17 mario Exp $
 */
package org.ceteca.explica.core.util;

import java.io.Serializable;
import java.util.ArrayList;

import org.xnap.commons.i18n.I18n;

/**
 * This class encapsulates the final result of any operation in the system,
 * plus the list of messages generated throughout the operation.
 * <br/>
 * Responsibilities:
 * <ul>
 * 	<li> Encapsulate and pass on the operation result to the end user. </li>
 *  <li> Keep the list of result messages generated througout the operation. </li>
 * </ul>
 * <br/>
 */
public class OperationResult implements Serializable {
	public static final int RESULT_OK = 0;
	public static final int RESULT_WARNING = -1;
	public static final int RESULT_ERROR = -2;
	public static final int RESULT_UNDEFINED = 1;
	
	private static final long serialVersionUID = 100001111;
	
	private ArrayList<ResultMessage> lResultMessages;
	private int result;
	
	public OperationResult() {
		this.lResultMessages = new ArrayList<ResultMessage>();
		result = this.RESULT_UNDEFINED;
	}
	
	public void addResultMessage(int result, ResultMessage msg) {
		this.lResultMessages.add(msg);
		
		// The final result of the operation will be built as the
		// result of all the messages generated throught the operation
		// execution. The result priorities must be considered, i.e.,
		// an error always prevails among the other types of messages and
		// in the same way, a warning prevails among ok messages.
		// The priority order is the following:
		// ERROR > WARNING > OK > UNDEFINED
		if (this.lResultMessages.size() > 0) {
			this.result = Math.min(result, this.result);
		}
		else {
			this.result = result;
		}
	}
	
	public ArrayList<ResultMessage> getResultMessagesList() {
		return this.lResultMessages;
	}
	
	public void clearResultMessagesList() {
		this.lResultMessages = new ArrayList<ResultMessage>();
	}

	public int getResult() {
		return result;
	}

	public void setResult(int result) {
		this.result = result;
	}
	
	public String getFormattedResult() {
		StringBuffer result = new StringBuffer();
		if (this.lResultMessages != null && this.lResultMessages.size() > 0) {
			for (int i=0; i<this.lResultMessages.size(); i++) {
				result.append(this.lResultMessages.get(i).getResMessage());
				result.append("\n");
			} // for each result message
		} // if there are any result messages
		else {
			result.append(" ---- NO RESULTS FOUND ----");
		}
		
		return result.toString();
	}
	
	public void add(OperationResult result) {
		if (result != null) {
			// Add the result messages of the
			if (result.getResultMessagesList() != null)
				this.lResultMessages.addAll(result.getResultMessagesList());
			
			// Set the result code
			this.result = Math.min(result.getResult(), this.result);
		}
	}
	
	/**
	 * Returns tag Id assigned to CVS source file.
	 */
	public static String getRevision() {
		return "$Id: OperationResult.java,v 1.1 2008-06-26 10:42:17 mario Exp $";
	}
}
